//
//  HDArchiveViewController.swift
//  HuaDaoPeifu
//
//  Created by Erickson on 16/3/28.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}

class HDArchiveViewController: UIViewController {
    var goingOnTableView = UITableView()
    var questionTableView = UITableView()
    var closeTableView = UITableView()
    var endTableView = UITableView()
    let doubleView = UIView()
    var goingOnList : [HDPolicyModel] = []
    var questionList : [HDPolicyModel] = []
    var closeList : [HDPolicyModel] = []
    var endList : [HDPolicyModel] = []
    var scrollerView = UIScrollView()
    var seg:SegmentControl?
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        doubleView.isHidden = true
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        doubleView.isHidden = false
        self.loadData(RefreshControl: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(HDArchiveViewController.userLogin), name: NSNotification.Name(rawValue: HDUserNotification.userlogin), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(HDArchiveViewController.userSignOut), name: NSNotification.Name(rawValue: HDUserNotification.userSignOut), object: nil)
        configUI()
        if HDAccountHandler.loginType == .notLogin {
//            scrollerView.isHidden = true
        } else {
            loadData(RefreshControl: nil)
        }
//        setupDoubleButton()
    }
    func configUI()  {
        let lineV = UIView()
        lineV.frame = CGRect(x: 0, y: 0, width: AppConstant.screenWidth, height: 10)
        lineV.backgroundColor = UIColor(red: 249/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1.0)
        self.view.addSubview(lineV)
        seg = SegmentControl.init(titles: ["进行中","问题件","关闭案件","已结案"], frame: CGRect(x: 0, y: 10, width: AppConstant.screenWidth, height: 37), images: nil, selImages: nil)
        seg?.tag = 200
        seg?.eventBlock = {(selectIndex:NSInteger) in
            switch selectIndex {
            case 0:
                self.scrollerView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
                break
            case 1:
                self.scrollerView.setContentOffset(CGPoint(x:AppConstant.screenWidth, y: 0), animated: false)
                break
            case 2:
                self.scrollerView.setContentOffset(CGPoint(x:AppConstant.screenWidth * 2, y: 0), animated: false)
                break
            case 3:
                self.scrollerView.setContentOffset(CGPoint(x:AppConstant.screenWidth * 3, y: 0), animated: false)
                break
            default:
                break
            }
        }
        self.view.addSubview(seg!)

        seg?.snp.makeConstraints({ (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(10)
            make.height.equalTo(37)
        })
        
        // scrollerView.frame = CGRect(x: 0, y: (seg?.frame.maxY)!, width: AppConstant.screenWidth, height: (AppConstant.screenHeight - 64 - 36 - 10))
        scrollerView.contentSize = CGSize(width: AppConstant.screenWidth * 4, height: 0)
        scrollerView.delegate = self
        scrollerView.isPagingEnabled = true
        scrollerView.showsHorizontalScrollIndicator = false
        scrollerView.isScrollEnabled = true
        
        self.view.addSubview(scrollerView)
        
        scrollerView.snp.makeConstraints { (make) in
            make.top.equalTo((seg?.snp.bottom)!)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.bottomLayoutGuide.snp.top)
        }
        
        // goingOnTableView.frame = CGRect(x: 0, y: 0, width: AppConstant.screenWidth, height: scrollerView.frame.size.height)
        
        goingOnTableView.delegate = self
        goingOnTableView.dataSource = self
        goingOnTableView.rowHeight = 95
        goingOnTableView.backgroundColor =  UIColor(red: 249/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1.0)
        goingOnTableView.separatorStyle = .none
        goingOnTableView.emptyDataSetSource = self as DZNEmptyDataSetSource
        goingOnTableView.emptyDataSetDelegate = self as DZNEmptyDataSetDelegate
         goingOnTableView.register(UINib(nibName: "HDInsuranceCell", bundle: nil), forCellReuseIdentifier: "HDInsuranceCell")
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction:#selector(loadData(RefreshControl:)))
        header?.lastUpdatedTimeLabel.isHidden = true
        header?.stateLabel.font = UIFont.systemFont(ofSize: 14)
        header?.setTitle("下拉刷新", for: .idle)
        header?.setTitle("松开刷新", for: .pulling)
        header?.setTitle("加载中...", for: .refreshing)
        goingOnTableView.mj_header = header
        scrollerView.addSubview(goingOnTableView)
        
        goingOnTableView.snp.makeConstraints { (make) in
            make.left.top.height.equalToSuperview()
            make.width.equalTo(AppConstant.screenWidth)
        }
        
        // questionTableView.frame = CGRect(x:AppConstant.screenWidth, y: 0, width: AppConstant.screenWidth, height: scrollerView.frame.size.height)
        questionTableView.delegate = self
        questionTableView.dataSource = self
        questionTableView.rowHeight = 95
        questionTableView.backgroundColor =  UIColor(red: 249/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1.0)
        questionTableView.separatorStyle = .none
        questionTableView.emptyDataSetSource = self as DZNEmptyDataSetSource
        questionTableView.emptyDataSetDelegate = self as DZNEmptyDataSetDelegate
        questionTableView.register(UINib(nibName: "HDInsuranceCell", bundle: nil), forCellReuseIdentifier: "HDInsuranceCell")
        let questionHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction:#selector(loadData(RefreshControl:)))
        questionHeader?.lastUpdatedTimeLabel.isHidden = true
        questionHeader?.stateLabel.font = UIFont.systemFont(ofSize: 14)
        questionHeader?.setTitle("下拉刷新", for: .idle)
        questionHeader?.setTitle("松开刷新", for: .pulling)
        questionHeader?.setTitle("加载中...", for: .refreshing)
        questionTableView.mj_header = questionHeader
        scrollerView.addSubview(questionTableView)
        questionTableView.snp.makeConstraints { (make) in
            make.top.height.equalToSuperview()
            make.width.equalTo(AppConstant.screenWidth)
            make.left.equalTo(goingOnTableView.snp.right)
        }
        
        
        // closeTableView.frame = CGRect(x:AppConstant.screenWidth * 2, y: 0, width: AppConstant.screenWidth, height: scrollerView.frame.size.height)
        closeTableView.delegate = self
        closeTableView.dataSource = self
        closeTableView.rowHeight = 95
        closeTableView.backgroundColor =  UIColor(red: 249/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1.0)
        closeTableView.separatorStyle = .none
        closeTableView.emptyDataSetSource = self as DZNEmptyDataSetSource
        closeTableView.emptyDataSetDelegate = self as DZNEmptyDataSetDelegate
        closeTableView.register(UINib(nibName: "HDInsuranceCell", bundle: nil), forCellReuseIdentifier: "HDInsuranceCell")
        let closeHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction:#selector(loadData(RefreshControl:)))
        closeHeader?.lastUpdatedTimeLabel.isHidden = true
        closeHeader?.stateLabel.font = UIFont.systemFont(ofSize: 14)
        closeHeader?.setTitle("下拉刷新", for: .idle)
        closeHeader?.setTitle("松开刷新", for: .pulling)
        closeHeader?.setTitle("加载中...", for: .refreshing)
        closeTableView.mj_header = closeHeader
        scrollerView.addSubview(closeTableView)
        closeTableView.snp.makeConstraints { (make) in
            make.top.height.equalToSuperview()
            make.width.equalTo(AppConstant.screenWidth)
            make.left.equalTo(questionTableView.snp.right)
        }
        
        
        // endTableView.frame = CGRect(x:AppConstant.screenWidth * 3, y: 0, width: AppConstant.screenWidth, height: scrollerView.frame.size.height)
        endTableView.delegate = self
        endTableView.dataSource = self
        endTableView.rowHeight = 95
        endTableView.backgroundColor =  UIColor(red: 249/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1.0)
        endTableView.separatorStyle = .none
        endTableView.emptyDataSetSource = self as DZNEmptyDataSetSource
        endTableView.emptyDataSetDelegate = self as DZNEmptyDataSetDelegate
        endTableView.register(UINib(nibName: "HDInsuranceCell", bundle: nil), forCellReuseIdentifier: "HDInsuranceCell")
        let endHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction:#selector(loadData(RefreshControl:)))
        endHeader?.lastUpdatedTimeLabel.isHidden = true
        endHeader?.stateLabel.font = UIFont.systemFont(ofSize: 14)
        endHeader?.setTitle("下拉刷新", for: .idle)
        endHeader?.setTitle("松开刷新", for: .pulling)
        endHeader?.setTitle("加载中...", for: .refreshing)
        endTableView.mj_header = endHeader
        scrollerView.addSubview(
            endTableView)
        endTableView.snp.makeConstraints { (make) in
            make.top.height.equalToSuperview()
            make.width.equalTo(AppConstant.screenWidth)
            make.left.equalTo((closeTableView.snp.right))
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        reloadTableViewData()
    }
    
    func setupDoubleButton() {
        tabBarController?.tabBar.hiddenBadgeValueAtItemIndex(1)
        tabBarController!.tabBar.addSubview(doubleView)
        let tap = UITapGestureRecognizer(target: self, action: #selector(HDArchiveViewController.doubleTapToRrefresh))
        
        tap.numberOfTapsRequired = 2
        doubleView.addGestureRecognizer(tap)
        doubleView.snp.remakeConstraints { (make) in
            make.bottom.equalTo(tabBarController!.tabBar.snp.bottom)
            make.height.equalTo(tabBarController!.tabBar.snp.height)
            make.width.equalTo(AppConstant.screenWidth / 3)
            make.centerX.equalTo(tabBarController!.tabBar.snp.centerX)
        }
    
        
    }
    
    func doubleTapToRrefresh() {
        if goingOnTableView.isHidden {
            return
        }
    tabBarController?.tabBar.hiddenBadgeValueAtItemIndex(0)
    }
    
    func userLogin() {
        loadData(RefreshControl: nil)
    }
    func userSignOut() {
        goingOnList = []
        questionList = []
        closeList = []
        endList = []
        goingOnTableView.reloadData()
        questionTableView.reloadData()
        closeTableView.reloadData()
        endTableView.reloadData()
        seg?.shouldShowBadgeViews(false)
    }
    
    func reloadTableViewData() {
        goingOnTableView.reloadData()
        questionTableView.reloadData()
        closeTableView.reloadData()
        endTableView.reloadData()
    }
    func loadData(RefreshControl refreshControl:MJRefreshNormalHeader?) {
        if refreshControl == nil {
            SVProgressHUD.showDisableLoading(nil)
        }
        HDApiManagerHandler.requestPolicylist { (result:HDFollowedPolicyListModel?) in
            guard let result = result
            else {
                
                if refreshControl != nil {
                    refreshControl?.endRefreshing()
                }else{
                    SVProgressHUD.dismiss()
                }
                return
            }
            
            self.goingOnList = result.part1 ?? []
            self.questionList = result.part2 ?? []
            self.closeList = result.part3 ?? []
            self.endList = result.part4 ?? []
            self.reloadTableViewData()

            if refreshControl != nil {
                refreshControl?.endRefreshing()
            }else{
                SVProgressHUD.dismiss()
            }
            self.seg?.setBadgeTitle([result.num1 ?? "0",result.num2 ?? "0",result.num3 ?? "0",result.num4 ?? "0"])
        }
    }
}
extension HDArchiveViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UIScrollViewDelegate{
    
    func imageTintColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
        return UIColor(red: 249/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1.0)
    }
    func customView(forEmptyDataSet scrollView: UIScrollView) -> UIView? {
        let v = UIView(frame: CGRect(x:0, y: 0, width: AppConstant.screenWidth, height: 200))
        let img = UIImage(named: "kongdingdan")
        let imgV = UIImageView(frame: CGRect(x:(AppConstant.screenWidth - 130) * 0.5, y: -150, width: 130, height: 100))
        imgV.image = img
        v.addSubview(imgV)
        
        let txtlabel = UILabel()
        txtlabel.frame = CGRect(x: 20, y:imgV.frame.maxY + 20, width: AppConstant.screenWidth - 40, height: 25)
        txtlabel.text = "暂无赔付案件，如需申请，请到“申请赔付”页面"
        txtlabel.font = UIFont.systemFont(ofSize: 15)
        txtlabel.textColor = UIColor(red: 102/255.0, green: 102/255.0, blue: 102/255.0, alpha: 1.0)
        txtlabel.textAlignment = .center
        v.addSubview(txtlabel)
        return v
    }
    func emptyDataSetWillAppear(_ scrollView: UIScrollView) {
        scrollView.contentOffset = CGPoint.zero
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == self.scrollerView{
            let seg = self.view.viewWithTag(200) as! SegmentControl
                let index = scrollView.contentOffset.x/AppConstant.screenWidth
                let indexInt = Int(index)
                seg.resetSelect(indexInt)
            if index == 1 {
                self.questionTableView.reloadData()
            }else if (index == 2){
                self.closeTableView.reloadData()
            }else if (index == 3){
                self.endTableView.reloadData()
            }
        }
    }
}
extension HDArchiveViewController : UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.goingOnTableView{
            return goingOnList.count
        }else if tableView == self.questionTableView{
            return questionList.count;
        }else if tableView == self.closeTableView{
            return closeList.count;
        }else{
          return endList.count;
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "HDInsuranceCell", for: indexPath) as! HDInsuranceCell
        if tableView == self.goingOnTableView {
            cell.archive = goingOnList[indexPath.row]
        }else if tableView == self.questionTableView {
            cell.archive = questionList[indexPath.row]
        }else if tableView == self.closeTableView {
            cell.archive = closeList[indexPath.row]
        }else{
            cell.archive = endList[indexPath.row]
        }
        return cell
    }
}

extension HDArchiveViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        var policy:HDPolicyModel?
            policy = self.goingOnList[indexPath.row]
        if tableView == self.goingOnTableView {
            policy = self.goingOnList[indexPath.row]
        }else if tableView == self.questionTableView {
            policy = self.questionList[indexPath.row]
        }else if tableView == self.closeTableView {
            policy = self.closeList[indexPath.row]
        }else{
            policy = self.endList[indexPath.row]
        }
        if  let poli = policy {
            if (poli.policyStatus == .PreAuditingSendBack||poli.policyStatus == .GiveUp) {
                let detail = HDPayDetailEitableViewController()
                detail.policy = poli
                navigationController?.pushViewController(detail, animated: true)
                tableView.deselectRow(at: indexPath, animated: true)
            }else{
                let detail = HDPayDetailViewController()
                detail.policy = poli
                navigationController?.pushViewController(detail, animated: true)
                tableView.deselectRow(at: indexPath, animated: true)
            }
        }
        
    }
}

extension HDArchiveViewController:HDImageBrowserViewControllerDelegate {
    func didFinishedRetakePhoto(_ imageDetail: HDUploadDetailImageModel) {
        print("didFinishedRetakePhoto----------调用了---------\(imageDetail.uploadImags.count)")
    }
}
